package com.free.bsf.metric.controller;

import com.free.bsf.core.base.BsfException;
import com.free.bsf.core.db.DbHelper;
import com.free.bsf.metric.base.Config;
import com.free.bsf.metric.base.SpringMvcController;
import com.free.bsf.metric.base.User;
import com.free.bsf.metric.dao.tb_sys_config_dal;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Controller
@RequestMapping("/")
public class HomeController extends SpringMvcController {
    @RequestMapping("/")
    public ModelAndView loginPage()
    {
        request.setAttribute("checkuser",false);
        return pageVisit((m) -> {
            m.setViewName("/home/login");
        });
    }
    /**
     * 登录
     * */
    @RequestMapping(value="/login",method= RequestMethod.POST)
    public ModelAndView login(String username,String password)
    {
        request.setAttribute("checkuser",false);
        return jsonVisit((m) -> {
            return DbHelper.get(Config.mysqlDataSource(),(c)->{
                tb_sys_config_dal dal = new tb_sys_config_dal();
                val user = dal.get(c,"users");
                if(user!=null){
                    for(val o:user.getM_value().split(";")) {
                        if(o.equals(username+":"+password)) {
                            val u = new User();
                            u.setUsername(username);
                            u.setRole(1);
                            u.setUserid(user.id);
                            val token = User.setCurrent(u);
                            return token;
                        }
                    }
                    throw new BsfException("账户密码出错");
                }else{
                    throw new BsfException("登陆失败");
                }
            });
        });
    }
    @RequestMapping("/loginout")
    public ModelAndView loginout()
    {
        User.setCurrent(null);
        return pageVisit((m) -> {
            m.setViewName("/home/login");
        });
    }
}
